package com.hudongwx.godoffood.fragment.communityFragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.hudongwx.godoffood.R;
import com.hudongwx.godoffood.activity.Community_Activity.DetailsActivity;
import com.hudongwx.godoffood.fragment.communityFragment.viewPager.ImageActivity;
import com.hudongwx.godoffood.utils.MyJsonObject;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 */
@ContentView(R.layout.fragment_recommend)
public class RecommendFragment extends Fragment {
    private View view = null;
    @ViewInject(R.id.Recommend_listview_1)
    private ListView listView1;
    @ViewInject(R.id.Recommend_listview_2)
    private RecyclerView listView2;
    private String postId;
    private JSONArray jsonPostData1;
    private String TAG = "RecommendFragment";

    public RecommendFragment() {
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (view == null) {
            view = x.view().inject(this, inflater, container);
            init();

        }
        return view;
    }

    @Event(R.id.change_tuijian)
    private void change(View view) {
        init();
    }

    private void init() {
        RequestParams requestParams = new RequestParams("http://api.shiandianping.com/api/sourceAndroidDianPing/v3.1.0/posts/GetGoodPost");
        x.http().get(requestParams, new Callback.CommonCallback<MyJsonObject>() {
            @Override
            public void onSuccess(MyJsonObject result) {
                initView(result);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.i(TAG, "onError: ");
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

        RequestParams requestParams2 = new RequestParams("http://api.shiandianping.com/api/sourceAndroidDianPing/v3.1.0/Posts");
        x.http().get(requestParams2, new Callback.CommonCallback<MyJsonObject>() {
            @Override
            public void onSuccess(MyJsonObject result) {
                init2View( parserListItem(result));
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    //初始化控件
    private void initView(JSONObject result) {
        MyListAdapter adapter = new MyListAdapter(result);
        try {
            jsonPostData1 = result.getJSONArray("Data");

        } catch (JSONException e) {
            e.printStackTrace();
        }
        listView1.setAdapter(adapter);
        listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    String postid=jsonPostData1.getJSONObject(position).getInt("Id")+"";
                    Intent intent =new Intent(getContext(), DetailsActivity.class);
                    intent.putExtra("postid",postid);
                    startActivity(intent);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    //初始化控件
    private void init2View(List<JSONObject> result) {
        MyShowAdapter adapter = new MyShowAdapter(result);
        LinearLayoutManager linearLayoutManager=new LinearLayoutManager(getContext());
        listView2.setAdapter(adapter);
        listView2.setLayoutManager(linearLayoutManager);

    }


    //创建一个适配器
    class MyListAdapter extends BaseAdapter {
        private JSONArray data;

        public MyListAdapter(JSONObject jsonObject) {
            try {
                this.data = jsonObject.getJSONArray("Data");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public int getCount() {
            return data.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return data.getJSONObject(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder;
            if (null == convertView) {
                convertView = LayoutInflater.from(getActivity()).inflate(R.layout.recommend_item1, null);
                viewHolder = new ViewHolder();
                viewHolder.iv = (ImageView) convertView.findViewById(R.id.Recommend_image);
                viewHolder.tv1 = (TextView) convertView.findViewById(R.id.Recommend_text1);
                viewHolder.tv2 = (TextView) convertView.findViewById(R.id.Recommend_text2);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            try {
                JSONObject item = data.getJSONObject(position);
                x.image().bind(viewHolder.iv, item.getString("CoverImg"));
                viewHolder.tv1.setText(item.getString("Title"));
                viewHolder.tv2.setText(item.getString("BoardName"));
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return convertView;
        }

        class ViewHolder {
            public ImageView iv;
            private TextView tv1;
            private TextView tv2;
        }
    }

    //适配器
    class MyShowAdapter extends RecyclerView.Adapter<MyViewHolder> {
        private List<JSONObject> data;

        public MyShowAdapter(List<JSONObject> list) {
            this.data = list;
        }

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            //设置parent 后才能让recyclerview的宽度才会不出错
            View view = LayoutInflater.from(getContext()).inflate(R.layout.recommend_item2, parent, false);
            return new MyViewHolder(view);
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int position) {
            try {
                setOnItemClickListener listener = new setOnItemClickListener();
                JSONObject item = data.get(position);
                JSONArray imageitem = item.getJSONArray("ListFile");
                holder.tv3.setText(item.getString("Title"));
                String content = item.getString("Content");
                if (!"".equals(content)) {
                    holder.tv4.setVisibility(View.VISIBLE);
                    holder.tv4.setText(item.getString("Content"));
                }
                ItemAdapter itemAdapter = new ItemAdapter(imageitem);
                holder.gridView.setAdapter(itemAdapter);
                postId = item.getString("Id") + "";
                holder.ll.setTag(postId);
                holder.ll.setOnClickListener(listener);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public int getItemCount() {
            return data.size();
        }
    }

    /**
     * 这是主item的装载器
     */
    class MyViewHolder extends RecyclerView.ViewHolder {

        private TextView  tv3, tv4;
        private GridView gridView;
        private LinearLayout ll;

        public MyViewHolder(View itemView) {
            super(itemView);
            gridView = (GridView) itemView.findViewById(R.id.showan_gridview);
            tv3 = (TextView) itemView.findViewById(R.id.showdan_tv3);
            tv4 = (TextView) itemView.findViewById(R.id.showdan_tv4);
            ll = (LinearLayout) itemView.findViewById(R.id.showdan_ll);
        }
    }
    /**
     * 这是小图片的适配器
     */
    class ItemAdapter extends BaseAdapter {
        private JSONArray data;
        //创建一个集合装载图片
        private ArrayList<String> list = new ArrayList<>();

        public ItemAdapter(JSONArray data) {
            this.data = data;
            addlist();
        }

        //将图片的地址添加进集合
        public void addlist() {
            for (int i = 0; i < data.length(); i++) {
                try {
                    list.add(data.getJSONObject(i).getString("Url"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public int getCount() {
            return data.length();

        }

        @Override
        public Object getItem(int position) {
            try {
                return data.getJSONObject(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageItemHolder imageItemHolder = null;
            gridViewClickListener gridViewclickListener = new gridViewClickListener();
            if (convertView == null) {
                imageItemHolder = new ImageItemHolder();
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.gridview_showdan_image, null);
                imageItemHolder.iv1 = (ImageView) convertView.findViewById(R.id.showdan_image3);
                convertView.setTag(imageItemHolder);
            } else {
                imageItemHolder = (ImageItemHolder) convertView.getTag();
            }
            try {
                String imageurl = data.getJSONObject(position).getString("Url");
                x.image().bind(imageItemHolder.iv1, imageurl);
                Map<String,Object> map=new HashMap<>();
                map.put("list",list);
                map.put("position",position);
                imageItemHolder.iv1.setTag(map);
                imageItemHolder.iv1.setOnClickListener(gridViewclickListener);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return convertView;
        }
    }

    class ImageItemHolder {
        private ImageView iv1;
    }

    //条目点击事件
    class setOnItemClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            String postid = (String) v.getTag();
            Intent intent = new Intent(getContext(), DetailsActivity.class);
            intent.putExtra("postid", postid);
            startActivity(intent);
        }
    }
    //gridview 的点击事件
    class gridViewClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            Map<String, Object> map = (Map<String, Object>) v.getTag();
            ArrayList<String> list = (ArrayList<String>) map.get("list");
            int position = (int) map.get("position");
            Intent intent = new Intent(getContext(), ImageActivity.class);
            intent.putExtra("position", position);
            intent.putStringArrayListExtra("list", list);
            startActivity(intent);
        }
    }
    /**
     * 把获取到的json数据，解析添加到一个List里面
     *
     * @param data
     * @return
     */
    private List<JSONObject> parserListItem(JSONObject data) {
        List<JSONObject> list = new ArrayList<>();
        try {
            JSONArray jsonArray = data.getJSONArray("Data");
            int len = jsonArray.length();
            for (int i = 0; i < len; i++) {
                list.add(jsonArray.getJSONObject(i));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }

}
